package com.pfzy.ui.activity.floatview;

import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.pfzy.ui.R;
import com.pfzy.ui.databinding.ActivityFloatBinding;
import com.pfzy.ui.utils.CheckPermissionUtils;

public class FloatActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityFloatBinding mBind;
    private final int OVERLAY_PERMISSION_REQ_CODE = 10001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBind = ActivityFloatBinding.inflate(getLayoutInflater());
        setContentView(mBind.getRoot());
        initView();
    }

    private void initView() {
        mBind.actFloatShow.setOnClickListener(this);
        mBind.actFloatHide.setOnClickListener(this);
        mBind.actFloatShow2.setOnClickListener(this);
        mBind.actFloatShow3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.act_float_show:
                boolean flag = getPermission();
                if (flag) {
                    Intent show = new Intent(this, TopWindowService.class);
                    show.putExtra(TopWindowService.OPERATION, TopWindowService.OPERATION_SHOW);
                    startService(show);
                }
                break;
            case R.id.act_float_hide:
                Intent hide = new Intent(this, TopWindowService.class);
                hide.putExtra(TopWindowService.OPERATION, TopWindowService.OPERATION_HIDE);
                startService(hide);
                break;
            case R.id.act_float_show2:
                initCustomWindow();
                break;
            case R.id.act_float_show3:
                show3();
                break;
        }
    }

    private boolean getPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                //打开设置页，让用户打开设置
                Toast.makeText(this, "can not DrawOverlays", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + this.getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
                return false;
            } else {
                // 已经打开了权限
                return true;
            }
        } else {
            // 6.0以下直接 Manifest申请该权限 就行。
            return true;
        }
    }

    private void initCustomWindow() {
        //6.0以上需要用户手动打开权限
        // (SYSTEM_ALERT_WINDOW and WRITE_SETTINGS, 这两个权限比较特殊，
        // 不能通过代码申请方式获取，必须得用户打开软件设置页手动打开，才能授权。Manifest申请该权限是无效的。)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                //打开设置页，让用户打开设置
                Toast.makeText(this, "can not DrawOverlays", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + this.getPackageName()));
                startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
            } else {
                // 已经打开了权限
                handleAddWindow();
            }
        } else {
            // 6.0以下直接 Manifest申请该权限 就行。
            handleAddWindow();
        }
    }

    private void handleAddWindow() {
        Button view = new Button(this);
        view.setText("添加到window中的button");

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                0, 0,
                PixelFormat.TRANSPARENT
        );
        // flag 设置 Window 属性
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        // type 设置 Window 类别（层级）：系统window
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
        }

        layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        layoutParams.x = 100;
        layoutParams.y = 100;

        WindowManager windowManager = getWindowManager();
        windowManager.addView(view, layoutParams);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case OVERLAY_PERMISSION_REQ_CODE:
                if (Settings.canDrawOverlays(this)) {
                    //打开了权限
                    handleAddWindow();
                } else {
                    Toast.makeText(this, "can not DrawOverlays", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void show3() {
        if (CheckPermissionUtils.getAppOps(this)) {
            if (FloatSecurityCenterView.getInstance(this).isValid()) {
                FloatSecurityCenterView.getInstance(this).showFloatView();
            } else {
                FloatSecurityCenterView.getInstance(this).createFloatView();
                FloatSecurityCenterView.getInstance(this).setType(0);
            }
        } else {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
    }
}